using FytSoa.Common.Enum;
using FytSoa.Domain.Erp;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using FytSoa.DynamicApi.Attributes;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Erp;

/// <summary>
/// erp生成订单详情-关联产品服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v9")]
public class ErpProduceDetailService : IApplicationService 
{
    private readonly SugarRepository<ErpProduceDetail> _thisRepository;
    private readonly SugarRepository<ErpProduceOrder> _orderRepository;
    private readonly SugarRepository<ErpBom> _bomRepository;
    private readonly SugarRepository<ErpBomProduct> _bomProductRepository;
    private readonly SugarRepository<ErpWarehouseProduct> _houseProductRepository;
    private readonly SugarRepository<ErpProduct> _productRepository;
    public ErpProduceDetailService(SugarRepository<ErpProduceDetail> thisRepository
        ,SugarRepository<ErpProduceOrder> orderRepository
        ,SugarRepository<ErpBom> bomRepository
    ,SugarRepository<ErpBomProduct> bomProductRepository
        ,SugarRepository<ErpWarehouseProduct> houseProductRepository
        ,SugarRepository<ErpProduct> productRepository)
    {
        _thisRepository = thisRepository;
        _orderRepository = orderRepository;
        _bomRepository = bomRepository;
        _bomProductRepository = bomProductRepository;
        _houseProductRepository = houseProductRepository;
        _productRepository = productRepository;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<List<ErpProduceDetailDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .Where(m=>m.OrderId==param.Id)
            .OrderByDescending(m=>m.Id)
            .ToListAsync();
        return query.Adapt<List<ErpProduceDetailDto>>();
    }
    
    /// <summary>
    /// 根据订单查询商品信息
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<List<ErpProduceDetailDto>> GetByOrderAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .Where(m => m.OrderId == param.Id)
            .Includes(m=>m.Product,p=>p.Unit)
            .OrderByDescending(m=>m.Id)
            .ToListAsync();
        return query.Adapt<List<ErpProduceDetailDto>>();
    }
    
    
    #region 根据产品编号查询涉及到的BOM信息
    private static readonly Random Random = new ();
    
    /// <summary>
    /// 根据产品编号查询涉及到的BOM信息
    /// </summary>
    /// <returns></returns>
    public async Task<List<ErpBomDetailedDto>> GetBomCostAsync(PageParam param)
    {
        var res = new List<ErpBomDetailedDto>();
        var order = await _thisRepository.GetListAsync(m=>m.OrderId==param.Id);
        // 根据产品查询bom信息
        var bomList = await _bomRepository.GetListAsync(m => order.Select(o => o.ProductId).Contains(m.ProductId));
        foreach (var item in bomList)
        {
            res.Add(new ErpBomDetailedDto()
            {
                Id = item.Id,
                ProductId = item.ProductId,
                ParentId = 0,
                IsBom = true,
                BomCount = order.FirstOrDefault(m=>m.ProductId==item.ProductId)!.Count,
                Version=item.Version,
            });
        }
        // 根据bom编号查询 bom组成子属性
        var bomProductList = await _bomProductRepository.GetListAsync(m=>bomList.Select(b=>b.Id).Contains(m.BomId));
        // 在根据子属性的产品编号，查询是否为bom组成
        var twoBomList =
            await _bomRepository.GetListAsync(m => bomProductList.Select(p => p.ProductId).Contains(m.ProductId));
        foreach (var item in bomProductList)
        {
            var parentBom = bomList.FirstOrDefault(m => m.Id == item.BomId);
            if (parentBom==null) continue;
            var orderModel = order.FirstOrDefault(m => m.ProductId == parentBom.ProductId);
            if (orderModel==null) continue;
            var orderCount = orderModel.Count;
            
            var productBomModel = twoBomList.FirstOrDefault(m => m.ProductId == item.ProductId);
            if (productBomModel==null)
            {
                res.Add(new ErpBomDetailedDto()
                {
                    Id = Random.Next(100000, 999999),
                    ProductId = item.ProductId,
                    ParentId = parentBom.Id,
                    BomCount = item.Count*orderCount
                });
            }
            else
            {
                res.Add(new ErpBomDetailedDto()
                {
                    Id = productBomModel.Id,
                    ProductId = item.ProductId,
                    ParentId = parentBom.Id,
                    IsBom = true,
                    Version = productBomModel.Version,
                    BomCount = item.Count*orderCount
                });
                var newRes = new List<ErpBomDetailedDto>();
                var newList=await GetBomProductAsync(productBomModel,newRes,orderCount);
                res.AddRange(newList);
            }
        }
        
        var productIds = res.Select(m => m.ProductId);
        //查询产品库存数
        var stockProduct=await _houseProductRepository.AsQueryable()
            .Where(m=>productIds.Contains(m.ProductId))
            .GroupBy(m=>m.ProductId)
            .Select(m => new
            {
                m.ProductId,
                Count = SqlFunc.AggregateSum(m.Count)
            })
            .ToListAsync();
        
        var productList = await _productRepository.GetListAsync(m => productIds.Contains(m.Id));
        foreach (var item in res)
        {
            var stockCount = 0;
            var stockModel = stockProduct.FirstOrDefault(m => m.ProductId == item.ProductId);
            if (stockModel!=null)
            {
                stockCount = stockModel.Count;
            }
            var productModel = productList.FirstOrDefault(m => m.Id == item.ProductId);
            if (productModel==null) continue;
            {
                item.Name = productModel.Name;
                item.ProductNumber = productModel.Number;
                item.ProductPrice = productModel.Price;
                item.BomPrice = productModel.Price;
                item.StockCount = stockCount;
            }
        }
        
        #region 查询领料信息

        var _applyRepository = _thisRepository.ChangeRepository<SugarRepository<ErpPurchaseApply>>();
        var applyIds = await _applyRepository.AsQueryable()
            .Where(m => m.OrderId == param.Id && m.Status==ErpProduceApplyEnum.Completed)
            .Select(m => m.Id)
            .ToListAsync();
        // 查询申领的产品
        var _applyProduceRepository = _thisRepository.ChangeRepository<SugarRepository<ErpPurchaseApplyProduct>>();
        var applyProduceList = await _applyProduceRepository.GetListAsync(m => applyIds.Contains(m.ApplyId));
        foreach (var item in res)
        {
            var appProduceModel = applyProduceList.FirstOrDefault(m => m.ProductId == item.ProductId);
            if (appProduceModel==null) continue;
            {
                item.PullCount = appProduceModel.Count;
            }
        }
        #endregion
        
        return res;
    }
    
    /// <summary>
    /// 根据物料编号查询bom组成信息
    /// </summary>
    /// <param name="bom"></param>
    /// <param name="res"></param>
    /// <returns></returns>
    [NonDynamicMethod]
    private async Task<List<ErpBomDetailedDto>> GetBomProductAsync(ErpBom bom ,List<ErpBomDetailedDto> res,int orderCount)
    {
        var bomProductList = await _bomProductRepository.GetListAsync(m => m.BomId == bom.Id);
        foreach (var item in bomProductList)
        {
            res.Add(new ErpBomDetailedDto()
            {
                Id = Random.Next(100000, 999999),
                ProductId = item.ProductId,
                ParentId = bom.Id,
                BomCount = item.Count*orderCount,
            });
        }
        return res;
    }
    
    #endregion

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ErpProduceDetailDto> GetAsync(long id)
    {
        var model = await _thisRepository.GetByIdAsync(id);
        return model.Adapt<ErpProduceDetailDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(ErpProduceDetailDto model) =>
        await _thisRepository.InsertAsync(model.Adapt<ErpProduceDetail>());

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(ErpProduceDetailDto model) =>
        await _thisRepository.UpdateAsync(model.Adapt<ErpProduceDetail>());

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody]List<long> ids) =>
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
}
